#include "BucketsAccess.h"
#include "../common/YXConstant.h"
#include "../common/YXJwt.h"
#include "../HttpFixedResponse.h"
#include "../ServerStruct.h"
#include "../cache/BucketCache.h"
#include "BucketsUtils.h"

#include <stdlib.h>

/**
 * 进行桶访问鉴权。
 * 若失败, 则会返回 YX_ERR 并设置 Response
 */
int bucket_access_check(Request *request, Response *response) {
    /* 获取文件前鉴权 */
    // 获取桶名
    char *bucket_name;
    if ((bucket_name = bucket_get_name_in_path(request->path)) == NULL) {
        set_response_bad_request(response, "Invalid path");
        return YX_ERR;
    }

    // 首先判断桶是否存在
    if (!bucket_cache_is_exist(bucket_name)) {
        free(bucket_name);
        set_response_bad_request(response, "Bucket does not exist");
        return YX_ERR;
    }

    // 获取桶的策略
    BucketCachedData *bucket_cached_data = bucket_cache_get(bucket_name);
    free(bucket_name);

    if (bucket_cached_data->access_policy == BUCKET_ACCESS_POLICY_PRIVATE) {
        // 进行校验令牌
        Claims *claims = yx_jwt_parse(request->token);
        if (claims == NULL) {
            set_response_unauthorized(response);
            return YX_ERR;
        }
        yx_jwt_claims_free(claims);
    }
    return YX_OK;
}